<?php

session_start();

require_once 'sys.inc';
require_once 'ajax.inc';

if (isset($_SESSION["user"]))
	$user = $_SESSION["user"];
else 
{
	echo "not logged";
	return;
}

$functions = array(
	"edit_profile" => new SafeFunc("edit_profile", array()),
	"update_profile" => new SafeFunc("update_profile", 
		array("old_password", "new_password", "cfm_password", "email")),
);

if (!run_function($functions))
	return;

/* AUX */	
function error_message($text)
{
?>	
<script type="text/javascript">

$(function(){
	message("<?php echo $text?>", "Error");
});

</script>
<?php 	
}

function info_message($text)
{
?>	
<script type="text/javascript">

$(function(){
	message("<?php echo $text?>", "Notice");
});

</script>
<?php 	
}

function isValidEmail($email)
{
	return preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$/i", $email);
}

/* END AUX */	

function edit_profile($arg)
{
	global $user;
	include_once 'tpl/ajax/edit-profile.tpl';
}


function update_profile($arg)
{
	global $user;
	global $table_admin;
	if (password_from_string($arg->old_password) != $user->password)
	{
		return error_message("Invalid password");
		
	}
	if ($arg->new_password != $arg->cfm_password)
	{
		return error_message("New/old password mismatch");
	}
	if (strlen($arg->new_password) < 3)
	{
		return error_message("New password too short");
	}
	if (!isValidEmail($arg->email))
	{
		return error_message("Email is not valid");
	}
	
	$pass = password_from_string($arg->new_password);
	
	mysql_query("UPDATE $table_admin SET password='$pass', email='$arg->email' 
		WHERE player_id=$user->player_id LIMIT 1");
	
	$user->password = $pass; 
	$user->email = $arg->email; 
	$_SESSION["user"] = $user;
	
	return info_message("Profile updated");
}



?>
